#include "widget.h"
#include "ui_widget.h"

#include<QNetworkDatagram>
const QString& SERVER_IP="127.0.0.1";
const quint16 PORT=8080;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端");
    socket=new QUdpSocket(this);

    connect(socket,&QUdpSocket::readyRead,this,[=](){
        const QNetworkDatagram responseDatagram=socket->receiveDatagram();
        QString response=responseDatagram.data();
        ui->listWidget->addItem(QString("服务端说")+response);
    });

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取到输入框的内容
    const QString& content=ui->lineEdit->text();
    //构造请求数据
    QNetworkDatagram requestDatagram(content.toUtf8(),QHostAddress(SERVER_IP),PORT);
    //发送请求
    socket->writeDatagram(requestDatagram);
    //消息添加到列表框中
    ui->listWidget->addItem("客户端说: "+content);
    //清空输入框
    ui->lineEdit->setText("");

}
